/**
 * @title  Firefox Extension: W3Grabber
 * @file   pageGrabber.js
 * @author Kasun Gajasinghe
 */
  
var responseText="";
var indexFileLocation;
var w3debug=false;
var linksDownloaded=new Array();
var initialLinks;
var fLocation="c:\\w3g_downloads\\";
var currentpageurl = "";
var dom; 
function chooseFolder(pageurl, pagedom, pagetitle){
	this.currentpageurl = pageurl;
	this.dom = pagedom;
	this.currentpagetitle=pagetitle;
	//Use a filepicker to choose the folder where all the downloaded files are saved.
	var nsIFilePicker = Components.interfaces.nsIFilePicker;
	var fp = Components.classes["@mozilla.org/filepicker;1"]
			.createInstance(nsIFilePicker);
	fp.init(window, "Select a Folder to save the web pages", nsIFilePicker.modeGetFolder);
	var res = fp.show(); 
	if (res == nsIFilePicker.returnOK) {
		  var file = fp.file;
		  this.fLocation = fp.file.path+"\\";//+pageDomain+"\\";
		  document.getElementById("folderLocText").value = this.fLocation;
	}else{ return;} 
}

function selector(choice, bookmInDel){
		//get the current page's url and save the page.
	//var pageurl = window.top.getBrowser().selectedBrowser.contentWindow.location.href;
	document.getElementById("download-label").value="Downloading...";	
	
	if(bookmInDel){ doDelicious(pageurl,pagetitle); } 
	
	var temp=pageurl;
	var pageDomain="";
	if(pageurl.match(/file:\/\/\//) != null){ temp=temp.substring(8);		//ex. file:///c:/files/index.html
		 pageDomain = temp.substring(0, temp.indexOf("/")); //ex: c:
		 pageDomain = pageDomain.replace(/:/,"");
	 }
	 else if(pageurl.match(/http:\/\//) != null) { //ex. http://www.example.com/index.html
		temp=temp.substring(7);		//ex. www.example.com/index.html
		 pageDomain = temp.substring(0, temp.indexOf("/")); //ex: www.example.com
	 } else{
		var sIndex = temp.indexOf("/");
		temp = temp.substring(sIndex+2);
		pageDomain = temp.substring(0, temp.indexOf("/"));
	}	
	pageDomain = pageDomain.replace("/","_");
	pageDomain = pageDomain.replace("\\","_");
	pageDomain = pageDomain.replace(":","_");
	
	if(w3debug) alert("loc="+fLocation);
	var tmpFLocation = this.fLocation+pageDomain+"\\";
	
	//create a directory if not exists
	var dir = DirIO.open(tmpFLocation);
	if (!dir.exists()) { 
		var rv = DirIO.create(dir);
	} 
	 if(choice==0){ domTester(pageurl,tmpFLocation);}
	 else if(choice==1) { saveImages(dom,fLocation);} 
	
	document.getElementById("download-label").value="All files downloaded.";	
}

function domTester(pageurl, tmpFLocation){ 
	//Create a index file with the redirection to the main file(i.e. currently opened page) of the site. 
	//This will be useful as users may not find it easy to locate the main file.
	indexFileLocation = tmpFLocation+"index.html";
	var filePath = tmpFLocation;
	filePath = createFolderStruct(tmpFLocation, pageurl);//indexFileLocation will changed to the correct location in here 
	savePage(pageurl, filePath);			//Save the current (main) page.
	
	indexFileLocation = indexFileLocation.replace(/\\/g,"/");	 
	var indexFileContent = "<html><head></head><body>If not automatically redirects, click <a href=\"file:///"+indexFileLocation+"\">here</a><script type=\"text/javascript\">window.location = 'file:///"+indexFileLocation+"';</script></body>";  
	var saveIndexPage = FileIO.open(tmpFLocation+"index.html");
	var writeStatus = FileIO.write(saveIndexPage, indexFileContent);
	if(!writeStatus) {
			alert("Error in writing the index file. Do you have enough permissions? ");
	}	 
	//var dom = gBrowser.contentDocument; //replaced due to gui requirements 
	domain = dom.domain;
	var links = dom.getElementsByTagName("a");
	initialLinks = links;
	getCssFiles(tmpFLocation,dom);
	saveAllLinks(tmpFLocation,links,"html");	 //Saves all the links in the page
	getImageFiles(tmpFLocation,dom);  
}

var counter=0;
var pageDepth = 3;	// The depth that the links to be saved.
			// for ex. if depth=1, then the currentpage with all the links will be saved.
			//if depth=2, then the links in the current page and links inside pages that current page will be saved. and so on for 3,4,...
var pageDepthCount=0;
function htmlToDom(baseLocation, link ){
	//if(counter>5) counter=0;
	var frame = document.getElementById("w3g-frame"+ (++counter));	
if (!frame) {
	// create frame
		frame = document.createElement("iframe"); // iframe
		frame.setAttribute("id", "w3g-frame"+counter);
		frame.setAttribute("name", "w3g-frame"+counter);
		frame.setAttribute("type", "content"); 
		frame.style.setProperty('min-height', "0px", 'important');
		frame.style.setProperty('height', "0px", 'important');
		frame.style.setProperty('min-width', "0px", 'important');
		frame.style.setProperty('width', "0px", 'important');
		 
		document.getElementById("w3g-main-window").appendChild(frame);

	// set restrictions as needed
		frame.webNavigation.allowAuth = true;
		frame.webNavigation.allowImages = false;
		frame.webNavigation.allowJavascript = false;
		frame.webNavigation.allowMetaRedirects = true;
		frame.webNavigation.allowPlugins = false;
		frame.webNavigation.allowSubframes = false;

	// listen for load
		frame.addEventListener("load", function (event) {
		  // the document of the HTML in the DOM
			var doc = event.originalTarget;
		  // skip blank page or frame
			if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return;
 
			var filePath = createFolderStruct(baseLocation,link); 
			savePage(link, filePath);	 
			getCssFiles(baseLocation,doc);	//doc is the DOM of the iframe document
			getImageFiles(baseLocation,doc);
			
		// when done remove frame or set location "about:blank"
			  setTimeout(function (){
				  var frame = document.getElementById("w3g-frame"+counter);
				  // remove frame
				  		// frame.destroy(); // if using browser element instead of iframe
						frame.contentDocument.location.href = "about:blank";
						frame.parentNode.removeChild(frame);
						
						
						alert("frame removed");
					// or set location "about:blank"
						// frame.contentDocument.location.href = "about:blank";
			  },10);
		}, true);
} 

// load a page  
	frame.contentDocument.location.href = link;  
		return; 
		
}
  
function getCssFiles(fLocation,dom){ 
 	var linkTags = dom.getElementsByTagName("link");	 //Save all CSS
	var cssLinks = new Array(); 
 	saveAllLinks(fLocation,linkTags,"css"); 
		
	var scriptTags = dom.getElementsByTagName("script");	 //Save all Javascript files
	var jsLinks = new Array();
 	saveAllLinks(fLocation,scriptTags,"js");  
}

function saveAllLinks(baseLocation,links,linkType){  
	 for (i=0;i<links.length;i++){  //ex. link=http://www.test.com/mail/inbox/index.php?name=123
		var link;
		if(linkType=="js") { link = links[i].src;}
		else {link =links[i].href;}
		
		if(link.match(/#/))	continue; 	//ignore Anchoring elements
		if(link.match(/mailto/)) continue;	//ignore links which are used to send emails
		if(link=="") continue;
		//htmlToDom(baseLocation, link);		
		var filePath = createFolderStruct(baseLocation,link); 
		savePage(link, filePath);	 //
	} 

}

function createFolderStruct(baseLocation,link){ 
		//Determine the File Path
		//subLocation implies the relative path from the baseLocation
		var subLocation=link;	
		subLocation = subLocation.replace("file:///","");//sublocation=http://www.test.com/mail/inbox/index.php?name=123 
													//affects if protocol is not http. 
		subLocation = subLocation.replace("://","");//sublocation=httpwww.test.com/mail/inbox/index.php?name=123 
		var startIndex = subLocation.indexOf("/");		//16 - (zero indexed)
		var lastIndex = subLocation.lastIndexOf("/");	//pts to '/' @ /index.php?name=123
		 
		subLocation = subLocation.substring(startIndex+1,lastIndex+1);	// sublocation=mail/inbox
		subLocation = subLocation.replace(/\//g,"\\");
		if(subLocation.indexOf("?") != -1) subLocation = subLocation.substring(0,subLocation.indexOf("?"));
		
		var finalLocation = baseLocation+subLocation;
		
		if(w3debug) alert("finLoc="+finalLocation+". subLoc="+subLocation+".base="+baseLocation);
	
		var dir = DirIO.open(finalLocation);
		if (!dir.exists())
		{
			var rv = DirIO.create(dir);
		}
		
		//determine the file name
		var nameSIndex = link.lastIndexOf("/");
		var nameLIndex = link.indexOf("?");
		//var namePart2="";
		if(nameLIndex == -1){nameLIndex = link.indexOf("#");}
		if(nameLIndex == -1){ nameLIndex = link.length;}
		//else { namePart2 = link.substring(link.indexOf("?")+1); alert("namepart2="+namePart2); }
		
		var fileName = link.substring(nameSIndex+1,nameLIndex);
		//fileName = fileName+namePart2;
		if(fileName=="") fileName="index.html";
		
		//check whether the file already exists
		
		//if(link==window.top.getBrowser().selectedBrowser.contentWindow.location.href){
		if(link==this.currentpageurl){
			indexFileLocation=finalLocation+fileName;
			if(w3debug) alert("redirected index file: "+indexFileLocation);
		} 
		return finalLocation+fileName;
		//savePage(link, finalLocation, fileName);
}

